
let { gameStuckDetection } = require('./utils/gameStuckDetection')

//安卓版本高于Android 9
if (device.sdkInt > 28) {
    //等待截屏权限申请并同意
    threads.start(function () {
        packageName('com.android.systemui').text('立即开始').waitFor();
        text('立即开始').click();
    });
}
//申请截屏权限
if (!requestScreenCapture(false)) {
    toast("请求截图失败");
    exit()
}

let loadingCount = 0

var storage = storages.create("wukuy4");

function _findImage(img, template, options) {
    if (options === undefined) options = {}
    let p = findImage(img, template, options);

    template.recycle()
    return p
}

function _matchTemplate(img, template, options) {
    let res = images.matchTemplate(img, template, options);

    template.recycle()
    return res
}

function _ocr(template) {
    let res = gmlkit.ocr(template, "zh");
    template.recycle()

    return res
}

function removeDuplicates(arr) {
    let list = [];
    return arr.filter((name) => !list.includes(name) && list.push(name))
}

const el = {
    _findMultiColors() {
        var img = captureScreen();
        let a = arguments

        return images.findMultiColors(
            img,
            a[0],
            a[1],
            a[2]
        )
    },
    isMain() {
        return this._findMultiColors(
            "#fceb8c", [[5, 0, "#df8941"], [11, 0, "#fbf369"], [15, 0, "#f4c94b"], [21, 1, "#f9f06c"], [29, 1, "#efb543"], [36, 3, "#f9d854"], [39, 3, "#da8937"]], { region: [470, 37, 47, 54], threshold: [26] }
        )
    },
    // 任务完成提示条
    task() {
        return this._findMultiColors(
            "#2b8755", [[45, 0, "#2b8755"], [91, -1, "#2b8755"], [32, 18, "#2b8755"]], { region: [1256, 199, 313, 90], threshold: [26] }
        )
    },
    /**  任务完成对话框 */
    taskFinishDialog() {
        return this._findMultiColors(
            "#ee343e", [[18, -18, "#ffffff"], [27, -18, "#ee343e"], [53, -13, "#ffffff"], [59, -18, "#ee343e"], [86, -20, "#ed333e"], [95, -18, "#f9b3b6"], [119, -17, "#fde9ea"], [139, -15, "#ffffff"], [146, -19, "#ee343e"]], { region: [661, 188, 256, 119], threshold: [26] }
        )
    },
    /** 去任务提示条 */
    taskDo() {
        return this._findMultiColors(
            "#ffeca5", [[32, 1, "#ffeca5"], [66, -1, "#ffeca5"], [73, 11, "#d4c48b"]], { region: [1260, 204, 307, 82], threshold: [26] }
        )
    },

    /** 孵化任务 */
    isIncubateTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/1.png'))
        return _findImage(img, templ, { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },
    /** 确认孵化按钮 */
    incubateBtn() {
        return this._findMultiColors(
            "#80a537", [[6, 2, "#152508"], [13, 1, "#80a537"], [18, 2, "#4f6b21"], [21, 3, "#182709"], [25, 3, "#80a537"], [33, 3, "#80a537"]], { region: [281, 741, 338, 102], threshold: [26] }
        )
    },

    /** 确认孵化按钮1 */
    incubateBtn1() {
        return this._findMultiColors(
            "#80a537", [[11, 2, "#0b1903"], [13, 2, "#6a8c2d"], [15, 2, "#0b1903"], [16, 2, "#506c22"], [19, 2, "#425a1c"], [20, 2, "#6c8d2e"], [22, 2, "#0b1903"], [24, 2, "#80a537"], [30, 2, "#0b1903"]], { region: [721, 631, 136, 52], threshold: [26] }
        )
    },

    /** 重生任务 */
    isRebornTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/2.png'))
        return _findImage(img, templ, { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },

    /** 重生任务 - 添加材料 */
    rebornTaskAdd() {
        var img = captureScreen();
        templ = images.read(files.path('./images/3.png'))
        return _findImage(img, templ, { region: [1095, 342, 1237 - 1095, 498 - 342] });
    },

    /** 重生任务确认按钮 */
    rebornTaskBtn() {
        var img = captureScreen();
        templ = images.read(files.path('./images/4.png'))
        return _findImage(img, templ);
    },
    /** 添加宠物到队伍 */
    isAddPetTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/5.png'))
        return _findImage(img, templ, { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },
    /** 添加宠物按钮 */
    addPetBtn() {
        var img = captureScreen();
        templ = images.read(files.path('./images/6.png'))
        mResult = _matchTemplate(img, templ)
        rightmost = undefined
        p = undefined

        if (mResult) {
            rightmost = mResult.rightmost()

            if (rightmost) {
                p = rightmost.point
            }
        }

        return p;
    },
    /** 添加宠物按钮1 */
    addPetBtn1() {
        var img = captureScreen();
        templ = images.read(files.path('./images/7.png'))
        return _findImage(img, templ);
    },
    /** 宠物升级 */
    isUpgradationTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/8.png'))
        temp2 = images.read(files.path('./images/26.png'))

        return _findImage(img, templ, { region: [1256, 204, 1568 - 1256, 286 - 204] }) || _findImage(img, temp2, { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },
    /** 挑战首领 */
    isChallengeTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/9.png'))
        temp2 = images.read(files.path('./images/21.png'))
        temp3 = images.read(files.path('./images/29.png'))
        temp4 = images.read(files.path('./images/31.png'))

        return _findImage(img, templ, { region: [1256, 204, 1568 - 1256, 286 - 204] }) || _findImage(img, temp2, { region: [1256, 204, 1568 - 1256, 286 - 204] }) || _findImage(img, temp3, { region: [1256, 204, 1568 - 1256, 286 - 204] }) || _findImage(img, temp4, { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },
    /** 加攻击属性 */
    isAddAttackAttributeTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/10.png'))
        return _findImage(img, templ, { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },
    /** 加攻击研究 */
    isAddAttackStudyTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/11.png'))
        return _findImage(img, templ);
    },
    /** 加速度属性 */
    isAddSpeedAttributeTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/12.png'))
        return _findImage(img, templ, { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },
    /** 召唤武器 */
    isCallWeaponTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/13.png'))
        return _findImage(img, templ) || _findImage(img, images.read(files.path('./images/69.png')));
    },
    /** 装备武器 */
    isEquipTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/14.png'))
        return _findImage(img, templ);
    },
    /** 装配技能任务 */
    isAssemblyConjurationTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/15.png'))
        return _findImage(img, templ, { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },
    /** 加生命研究 */
    isAddLifeStudyTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/16.png'))
        return _findImage(img, templ);
    },
    /** 召唤项链任务 */
    isNecklaceTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/17.png'))
        temp2 = images.read(files.path('./images/34.png'))

        return _findImage(img, templ) || _findImage(img, temp2);
    },
    /** 装备升级任务 */
    isEquipmentUpgradeTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/18.png'))
        return _findImage(img, templ, { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },
    /** 加再生研究 */
    isAddRegenerationStudyTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/19.png'))
        return _findImage(img, templ, { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },
    /** 加防御研究 */
    isAddDefenseStudyTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/20.png'))
        return _findImage(img, templ, { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },
    /** ok */
    ok() {
        var img = captureScreen();
        templ = images.read(files.path('./images/22.png'))
        temp2 = images.read(files.path('./images/23.png'))
        temp3 = images.read(files.path('./images/28.png'))
        temp6 = images.read(files.path('./images/ok.png'))
        temp7 = images.read(files.path('./images/ok1.png'))
        temp4 = images.read(files.path('./images/ok2.png'))
        temp5 = images.read(files.path('./images/ok3.png'))

        return _findImage(img, temp5) || _findImage(img, temp3) || _findImage(img, temp2) || _findImage(img, templ) || _findImage(img, temp4) || _findImage(img, temp6) || _findImage(img, temp7);
    },
    /** 升级技能任务 */
    isUpgradeSkillsTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/24.png'))
        return _findImage(img, templ, { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },
    /** 宠物进化 */
    isPetEvolutionTask() {
        var img = captureScreen();
        templ = images.read(files.path('./images/27.png'))
        return _findImage(img, templ);
    },

    /** 主界面宠物升级 */
    mainPetUpgradation() {
        var img = captureScreen();
        templ = images.read(files.path('./images/32.png'))
        return _findImage(img, templ, { region: [30, 157, 221 - 30, 337 - 157], threshold: 0.9 });
    },

    /** 宠物进化、升级 */
    petUpgradation() {
        var img = captureScreen();
        templ = images.read(files.path('./images/33.png'))
        return _matchTemplate(img, templ, { region: [241, 720, 692 - 241, 827 - 720] });
    },
    /** 主界面-宠物入口 */
    mainPet() {
        var img = captureScreen();
        templ = images.read(files.path('./images/35.png'))
        return _findImage(img, templ);
    },
    /** 宠物列表界面 */
    isPetList() {
        var img = captureScreen();
        templ = images.read(files.path('./images/36.png'))
        return _findImage(img, templ)
    },

    /** 升阶任务 */
    isDanTask() {
        return _findImage(captureScreen(), images.read(files.path('./images/38.png')), { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },
    /** 送走宠物任务 */
    isSendAwayPetTask() {
        return _findImage(captureScreen(), images.read(files.path('./images/54.png')), { region: [1256, 204, 1568 - 1256, 286 - 204] });
    },
    /** 获得技能任务 */
    isAddSkillTask() {
        return _findImage(captureScreen(), images.read(files.path('./images/59.png')), { region: [1256, 204, 1568 - 1256, 286 - 204], threshold: 0.95 })
    },
    /** 装配技能任务 */
    isAssembleSkillTask() {
        return _findImage(captureScreen(), images.read(files.path('./images/60.png')), { region: [1256, 204, 1568 - 1256, 286 - 204] })
    },
    /** 元素副本任务 */
    isElementCopyTask() {
        return _findImage(captureScreen(), images.read(files.path('./images/61.png')), { region: [1256, 204, 1568 - 1256, 286 - 204] })
    },
    /** 召唤师信息-升阶 */
    isUserInfo() {
        return _findImage(captureScreen(), images.read(files.path('./images/召唤师信息-升阶.png')), { region: [1275, 160, 1564 - 1275, 294 - 160] })
    }
}

const modules = {
    /** 宠物升级 */
    upgradationPet(isMax) {
        p = _findImage(captureScreen(), images.read(files.path('./images/宠物升级按钮.png')), { region: [234, 723, 703 - 234, 834 - 723] });
        if (p) {
            console.log('宠物升级');
            click(p.x, p.y)
            sleep(1000)
            p = _findImage(captureScreen(), images.read(files.path('./images/up/max.png')));
            sleep(40)
            if (p) {
                if (isMax) {
                    console.log('加max');
                    click(p.x, p.y)
                } else {
                    console.log('加100');
                    click(1313, 551)
                }
                sleep(1000)
                p = _findImage(captureScreen(), images.read(files.path('./images/up/升级.png')), { region: [799, 676, 1310 - 799, 798 - 676] });
                if (p) {
                    click(p.x, p.y)
                    sleep(4000)
                }
            }
            p = _findImage(captureScreen(), images.read(files.path('./images/30.png')), { region: [859, 107, 1513 - 859, 623 - 107], threshold: 0.7 });
            if (p) {
                click(p.x + 20, p.y + 20)
                sleep(3000)
            }
        }
    },
    /** 宠物进化 */
    evolutionPet(rarityNo) {
        let count = 0
        do {
            let p = _findImage(captureScreen(), images.read(files.path('./images/up/进化.png')), { region: [234, 723, 703 - 234, 834 - 723] });

            let currentCardPoint = el._findMultiColors("#f2ff5b", [[116, 0, "#f4ff59"], [-2, 144, "#f1ff58"], [116, 143, "#b6ff10"]], { region: [711, 200, 1578 - 711, 899 - 200], threshold: [26] })

            if (!currentCardPoint) {
                break
            }
            let petInfo = modules.getPetAttribute([currentCardPoint.x, currentCardPoint.y, 110, 140])

            if (Number(petInfo.rarityNo) >= Number(rarityNo)) {
                console.log('宠物进升完成');
                console.log(petInfo);
                break
            }

            if(count > 3) {
                console.log('缺少水晶石');
                break
            }

            if (p) {
                console.log('宠物进化');

                click(p.x, p.y)
                sleep(1000)

                res = _matchTemplate(captureScreen(), images.read(files.path('./images/up/进化卡片标识.png')), { region: [705, 322, 1408 - 705, 503 - 322] })

                let img = captureScreen()
                let evolutionNeed = res.points.map((p, idx) => {
                    let x = p.x
                    let y = p.y - 144
                    let width = 110
                    let height = 140

                    let res = _ocr(images.clip(img, x, y + 120, width, 50), "zh");

                    if (res) {
                        if (findColor(img, "#FF5F5F", { region: [x, y, width, height] })) {
                            lackNum = 0
                            stoneName = ''

                            if (idx > 0) {
                                let arr = res.text.split('/')
                                arr[0] = arr[0].replace('o', 0)

                                if (arr.length) {
                                    lackNum = arr[1] - arr[0]
                                }

                                if (findImage(img, images.read(files.path('./images/up/火元素.png')), { region: [x, y, width, height] })) {
                                    stoneName = '火'
                                } else if (findImage(img, images.read(files.path('./images/up/风元素.png')), { region: [x, y, width, height] })) {
                                    stoneName = '风'
                                } else if (findImage(img, images.read(files.path('./images/up/水元素.png')), { region: [x, y, width, height] })) {
                                    stoneName = '水'
                                } else if (findImage(img, images.read(files.path('./images/up/光明元素.png')), { region: [x, y, width, height] })) {
                                    stoneName = '光明'
                                } else if (findImage(img, images.read(files.path('./images/up/进化石.png')), { region: [x, y, width, height] })) {
                                    stoneName = '进化石'
                                }
                            }
                            return {
                                lackNum,
                                type: idx === 0 ? 'level' : 'stone',
                                stoneName
                            }
                        }
                    }
                }).filter(item => item)

                if (evolutionNeed.length) {
                    modules.close('inner')

                    count += 1

                    // 等级不够
                    if (evolutionNeed[0].type == 'level') {
                        modules.upgradationPet(true)
                        continue
                    }

                    // 需要购买石头
                    if (evolutionNeed.find(item => item.type == 'stone')) {
                        modules.close()
                        // 购买石头
                        evolutionNeed.forEach(item => {
                            if (item.type == 'stone') {
                                modules.purchaseStone(item.stoneName, item.lackNum)
                            }
                        })
                    }

                    if (el.isMain()) {
                        let p = el.mainPet()
                        if (p) {
                            click(p.x, p.y)
                            sleep(2000)
                            if (currentCardPoint) {
                                click(currentCardPoint.x + 50, currentCardPoint.y + 50)
                                sleep(1000)

                                let p = _findImage(captureScreen(), images.read(files.path('./images/up/进化.png')), { region: [234,723,703 - 234,834 - 723] });

                                if(p) {
                                    click(p.x, p.y)
                                    sleep(1000)
                                }
                            } else {
                                console.log('没有currentCardPoint数据');
                            }
                        }
                    }
                }else {
                    p = _findImage(captureScreen(), images.read(files.path('./images/up/进化.png')));

                    if (p) {
                        click(p.x, p.y)
                        sleep(3000)
                        modules.ok()
                        sleep(2000)
                        modules.ok()
                    }
                }

                modules.close('inner')
            }
        } while (rarityNo);
    },
    /** 宠物重生 */
    reborn(levelNo) {
        // 重生按钮
        let btn = _findImage(captureScreen(), images.read(files.path('./images/up/重生按钮.png')), { region: [234, 723, 703 - 234, 834 - 723] })

        if (btn) {
            let currentCardPoint = el._findMultiColors("#f2ff5b", [[116, 0, "#f4ff59"], [-2, 144, "#f1ff58"], [116, 143, "#b6ff10"]], { region: [711, 200, 1578 - 711, 899 - 200], threshold: [26] })

            do {
                if (levelNo) {
                    modules.upgradationPet()
                    petInfo = modules.getPetAttribute([currentCardPoint.x, currentCardPoint.y, 110, 140])

                    if (petInfo.levelNo >= levelNo) {
                        console.log(petInfo);
                        break
                    }
                }

                click(btn.x, btn.y)
                sleep(1500)

                // 最后一次重生
                let p = _findImage(captureScreen(), images.read(files.path('./images/ok4.png')), { region: [491, 282, 1160 - 491, 707 - 282] })
                if (p) {
                    click(p.x, p.y)
                    sleep(1500)
                }

                // 需要选择重生石
                p = el.rebornTaskAdd()
                if (p) {
                    // 添加重生石
                    click(p.x, p.y)
                    sleep(2000)
                    // 确认选择
                    click(434, 730)
                    sleep(1500)
                }

                // 重生按钮
                p = _findImage(captureScreen(), images.read(files.path('./images/up/重生按钮.png')), { region: [814, 675, 1311 - 814, 804 - 675] })
                if (p) {
                    click(p.x, p.y)
                    sleep(2000)

                    // 确认重生
                    p = el.rebornTaskBtn()
                    if (p) {
                        click(p.x, p.y)
                        sleep(2000)
                        modules.ok()
                    }
                }

                p = _findImage(captureScreen(), images.read(files.path('./images/up/选择召唤兽.png')), { region: [427, 72, 1471 - 427, 599 - 72] })
                if (p) {
                    modules.close('inner')
                    modules.close('inner')
                }

            } while (levelNo)
        }

    },
    /** 孵化 */
    incubate(options) {
        let { type, num } = options || {}
        if (!num) num = 1
        let p = _findImage(captureScreen(), images.read(files.path('./images/35.png')))

        if (p) {
            click(p.x, p.y)
            sleep(1000)

            console.log('点击孵化')
            click(107, 429)
            sleep(3000)

            // 孵化列表
            res = _matchTemplate(captureScreen(), images.read(files.path('./images/up/孵化界面宠物标识.png')), { max: 35, region: [728, 219, 1560 - 728, 858 - 219], threshold: 0.9 })

            incubateList = res.sortBy('top-left').points.map(p => {
                x = p.x - 84
                y = p.y - 120
                width = 110
                height = 140
                region = [x, y, width, height]

                return modules.getPetAttribute(region)
            }).filter(item => item.type)

            if (incubateList.length) {
                // 按条件过滤数据
                if (type) {
                    incubateList = incubateList.filter(item => item.type == type)
                }
                if (num) {
                    incubateList = incubateList.slice(0, num)
                }
            }

            incubateList.forEach(item => {
                let [x, y] = item.region

                console.log('孵化', item);
                click(x + 40, y + 60)
                sleep(1000)

                console.log('使用');
                click(536, 794)
                sleep(1000)

                let p = _findImage(captureScreen(), images.read(files.path('./images/up/孵化.png')))

                if (p) {
                    click(p.x, p.y)
                    sleep(3000)
                }
                modules.ok()
            })

            modules.close()
        }
    },
    /** 领取奖励 */
    receiveReward() {
        /** 新手排名 */
        p = _findImage(captureScreen(), images.read(files.path('./images/37.png')), { region: [418, 52, 455 - 418, 83 - 52] })

        let get = () => {
            p = _findImage(captureScreen(), images.read(files.path('./images/领取奖励.png')))
            if (p) {
                click(p.x, p.y)
                sleep(1000)

                click(924, 733)
                sleep(3000)
            }
        }

        if (p) {
            click(p.x, p.y)
            sleep(3000)

            var img = captureScreen();
            templ = images.read(files.path('./images/37.png'))
            res = _matchTemplate(img, templ, { region: [281, 150, 1309 - 281, 234 - 150] });
            arr = res.sortBy('left').points

            if (arr.length) {
                arr.forEach(p => {
                    click(p.x - 40, p.y + 12)
                    sleep(1000)

                    do {
                        p = _findImage(captureScreen(), images.read(files.path('./images/领取奖励圆点.png')), { region: [1030, 224, 1478 - 1030, 374 - 224] })

                        if (p) {
                            click(p.x - 40, p.y + 30)
                            sleep(2000)

                            get()
                        }
                    } while (p);

                    get()
                })
            }

            // 关闭按钮
            click(1456, 185)
            sleep(1000)
        }

        /** 排名奖励 */
        p = images.findColorEquals(captureScreen(), '#F04545', 1201, 28, 1223 - 1201, 50 - 28)

        if (p) {
            click(p.x, p.y)
            sleep(3000)

            var img = captureScreen();
            templ = images.read(files.path('./images/37.png'))
            res = _matchTemplate(img, templ, { region: [281, 150, 1309 - 281, 234 - 150] });
            arr = res.sortBy('left').points

            if (arr.length) {
                arr.forEach(p => {
                    click(p.x - 40, p.y + 12)
                    sleep(3000)

                    do {
                        p = _findImage(captureScreen(), images.read(files.path('./images/领取奖励圆点.png')), { region: [1030, 224, 1478 - 1030, 374 - 224] })

                        if (p) {
                            click(p.x - 40, p.y + 30)
                            sleep(2000)

                            get()
                        }
                    } while (p);

                    get()
                })
            }

            // 关闭按钮
            click(1456, 185)
            sleep(1000)
        }

        /** 领取任务奖励 */
        p = images.findColorEquals(captureScreen(), '#F04545', 1276, 29, 1296 - 1276, 51 - 29)
        if (p) {
            click(p.x, p.y)
            sleep(3000)

            var img = captureScreen();
            templ = images.read(files.path('./images/37.png'))
            res = _matchTemplate(img, templ, { region: [281, 150, 1309 - 281, 234 - 150] });
            arr = res.sortBy('left').points

            if (arr.length) {
                arr.forEach(p => {
                    click(p.x - 40, p.y + 12)
                    sleep(1000)
                    // 领取
                    click(1241, 731)
                    sleep(4000)
                    // 确认
                    click(800, 614)
                    sleep(1000)
                })
            }

            // 关闭按钮
            click(1387, 187)
            sleep(1000)
        }

        /** 通关奖励 */
        p = images.findColorEquals(captureScreen(), '#F04545', 1347, 27, 1371 - 1347, 52 - 27)
        if (p) {
            click(p.x, p.y)
            sleep(3000)
            res = _matchTemplate(captureScreen(), images.read(files.path('./images/37.png')), { region: [26, 142, 195 - 26, 898 - 142] });
            arr = res.sortBy('left').points

            if (arr.length) {
                arr.forEach(p => {
                    click(p.x - 20, p.y + 12)
                    sleep(1000)

                    res = _matchTemplate(captureScreen(), images.read(files.path('./images/37.png')), { region: [331, 142, 1477 - 331, 228 - 142] });
                    arr = res.sortBy('left').points
                    arr.forEach(p => {
                        click(p.x - 20, p.y + 12)
                        sleep(1000)
                        // 领取奖励
                        click(1411, 297)
                        sleep(3000)

                        // 确认
                        click(807, 609)
                        sleep(1000)
                    })
                })
            }

            // 关闭按钮
            click(1512, 58)
            sleep(1000)
        }

        /** 信箱奖励 */
        p = images.findColorEquals(captureScreen(), '#F04545', 1422, 26, 1449 - 1422, 56 - 26)
        if (p) {
            click(p.x, p.y)
            sleep(3000)
            click(1253, 736)
            sleep(3000)

            // 确定
            p = _findImage(captureScreen(), images.read(files.path('./images/ok.png')))
            if (p) {
                click(p.x, p.y)
                sleep(1000)
            }

            // 关闭对话框
            click(1385, 184)
            sleep(1000)
        }

    },
    /** 放置宠物 */
    placePet() {
        res = _matchTemplate(captureScreen(), images.read(files.path('./images/6.png')))

        if (res) {
            arr = res.sortBy('left').points
            arr.forEach(p => {
                click(p.x, p.y)
                sleep(1000)
                p = _findImage(captureScreen(), images.read(files.path('./images/42.png')), { region: [678, 730, 966 - 678, 834 - 730] })
                if (p) {
                    click(p.x, p.y)
                    sleep(1000)

                    p = _findImage(captureScreen(), images.read(files.path('./images/25.png')), { region: [231, 340, 1040 - 231, 783 - 340] })

                    if (p) {
                        click(p.x + 100, p.y + 200)
                        sleep(1000)
                    }
                }
            })
        }
    },
    /** 做任务 */
    doTasks() {
        // 完成任务，领取奖励
        let p = el.task()

        if (p) {
            console.log('领取任务奖励');
            click(1412, 246)
            sleep(2000)
            click(763, 599)
            sleep(1000)
        }

        // 点击做任务
        let p1 = el.taskDo()

        if (p1) {
            console.log('做任务');
            incubateTask = el.isIncubateTask()
            sleep(50)
            rebornTask = el.isRebornTask()
            sleep(50)
            addPetTask = el.isAddPetTask()
            sleep(50)
            upgradationTask = el.isUpgradationTask()
            sleep(50)
            challengeTask = el.isChallengeTask()
            sleep(50)
            addAttackAttributeTask = el.isAddAttackAttributeTask()
            sleep(50)
            addAttackStudyTask = el.isAddAttackStudyTask()
            sleep(50)
            addSpeedAttributeTask = el.isAddSpeedAttributeTask()
            sleep(50)
            callWeaponTask = el.isCallWeaponTask()
            sleep(50)
            equipTask = el.isEquipTask()
            // sleep(50)
            // assemblyConjurationTask = el.isAssemblyConjurationTask()
            sleep(50)
            lifeStudyTask = el.isAddLifeStudyTask()
            sleep(50)
            necklaceTask = el.isNecklaceTask()
            sleep(50)
            equipmentUpgradeTask = el.isEquipmentUpgradeTask()
            sleep(50)
            addRegenerationStudyTask = el.isAddRegenerationStudyTask()
            sleep(50)
            addDefenseStudyTask = el.isAddDefenseStudyTask()
            sleep(50)
            upgradeSkillsTask = el.isUpgradeSkillsTask()
            sleep(50)
            petEvolutionTask = el.isPetEvolutionTask()
            if (petEvolutionTask) {
                modules.close()
                modules.incubate()
                sleep(1000)
                if (el.isMain()) {
                    let p = el.mainPet()
                    if (p) {
                        click(p.x, p.y)
                        sleep(2000)
                        if (el.isPetList()) {
                            let pets = modules.getPetList()
                            pets = pets.filter(item => item.level == '?')

                            if (pets.length) {
                                p = pets[0].region
                                x = p[0]
                                y = p[1]

                                click(x + 70, y + 50)
                                sleep(1000)

                                modules.upgradationPet()
                                modules.evolutionPet()
                            }
                        }
                    }
                }
            }
            sleep(50)
            danTask = el.isDanTask()
            sleep(50)
            sendAwayPetTask = el.isSendAwayPetTask()
            sleep(50)
            addSkillTask = el.isAddSkillTask()
            sleep(50)
            assembleSkillTask = el.isAssembleSkillTask()
            sleep(50)
            elementCopyTask = el.isElementCopyTask()
            sleep(50)
            // 获取技能2
            isObtainFirewallTask = _findImage(captureScreen(), images.read(files.path('./images/63.png')), { region: [1256, 204, 1568 - 1256, 286 - 204], threshold: 0.95 })
            sleep(50)
            // 获取技能3
            isObtainAdvancedTrainingTask = _findImage(captureScreen(), images.read(files.path('./images/64.png')), { region: [1256, 204, 1568 - 1256, 286 - 204], threshold: 0.95 })
            sleep(50)
            // 获取闪电技能
            isObtainLightningTask = _findImage(captureScreen(), images.read(files.path('./images/70.png')), { region: [1256, 204, 1568 - 1256, 286 - 204], threshold: 0.95 })
            sleep(50)
            // 副本金币任务
            isCopyGoldCoinTask = _findImage(captureScreen(), images.read(files.path('./images/65.png')), { region: [1256, 204, 1568 - 1256, 286 - 204] })
            sleep(50)
            // 副本草药任务
            isHerbMedicineTask = _findImage(captureScreen(), images.read(files.path('./images/66.png')), { region: [1256, 204, 1568 - 1256, 286 - 204] })
            sleep(50)
            // 矿山任务
            isMineTask = _findImage(captureScreen(), images.read(files.path('./images/68.png')), { region: [1256, 204, 1568 - 1256, 286 - 204] })
            sleep(50)
            // 武器交换宠物
            isWeaponExchangePetsTask = _findImage(captureScreen(), images.read(files.path('./images/67.png')), { region: [1256, 204, 1568 - 1256, 286 - 204] })
            sleep(50)

            click(p1.x, p1.y)
            sleep(1500)

            if (incubateTask) {
                console.log('孵化任务');
                p = el.incubateBtn()

                if (p) {
                    click(p.x, p.y)
                    sleep(2000)

                    p = el.incubateBtn1()

                    if (p) {
                        click(p.x, p.y)
                        sleep(2000)

                        click(763, 793)
                    }
                }
            }
            if (rebornTask) {
                console.log('重生任务');
                // 宠物列表重新排序筛选
                modules.filterPetList()
                sleep(1000)
                let ordinaryPets = modules.getPetList()
                // let ordinaryPets = petList.filter(item => item.rarityNo == 1)

                if (ordinaryPets.length) {
                    pet = ordinaryPets[random(0, ordinaryPets.length - 1)]

                    if (pet) {
                        x = pet.region[0] + 50
                        y = pet.region[1] + 50

                        click(x, y)
                        sleep(1000)

                        modules.reborn()
                    }
                }
            }
            if (addPetTask) {
                console.log('添加宠物到队伍');

                modules.close()
                modules.incubate()

                click(1394, 238)
                sleep(1000)
                modules.petSort('up', '获得')
                modules.placePet()
            }
            if (upgradationTask) {
                console.log('宠物升级');

                let ordinaryPets = modules.getPetList()

                if (ordinaryPets.length) {
                    pet = ordinaryPets[random(0, ordinaryPets.length - 1)]
                    p = pet.region

                    x = p[0] + 50
                    y = p[1] + 50

                    click(x, y)
                    sleep(1000)

                    modules.upgradationPet()
                }
            }
            if (challengeTask) {
                console.log('挑战首领');
                click(992, 183)
                sleep(1000)
            }
            if (addAttackAttributeTask) {
                console.log('加攻击属性');
                for (let idx = 0; idx < 20; idx++) {
                    click(426, 592)
                    sleep(500)
                }
            }
            if (addAttackStudyTask) {
                console.log('加攻击研究');
                for (let idx = 0; idx < 20; idx++) {
                    click(391, 411)
                    sleep(500)
                }
            }
            if (addSpeedAttributeTask) {
                console.log('加速度属性');
                for (let idx = 0; idx < 20; idx++) {
                    click(913, 407)
                    sleep(500)
                }
            }
            if (callWeaponTask) {
                console.log('召唤武器');
                click(1336, 756)
                sleep(1000)
                click(919, 600)
                sleep(5000)
                click(954, 776)
                sleep(1000)
            }
            if (equipTask) {
                console.log('装备武器');
                click(730, 775)
                sleep(1000)
            }
            // if(assemblyConjurationTask) {
            //     console.log('装配技能任务');
            //     click(869,790)
            //     sleep(1000)
            // }
            if (lifeStudyTask) {
                console.log('加生命研究');
                for (let idx = 0; idx < 20; idx++) {
                    click(1158, 413)
                    sleep(500)
                }
            }

            if (necklaceTask) {
                console.log('召唤项链任务');
                click(1336, 756)
                sleep(1000)
                click(919, 600)
                sleep(5000)
                click(954, 776)
                sleep(1000)
            }
            if (equipmentUpgradeTask) {
                console.log('装备升级任务');
                click(881, 773)
                sleep(1000)
                click(927, 736)
                sleep(3000)
                click(803, 613)
                sleep(1000)
            }
            if (addRegenerationStudyTask) {
                console.log('加再生研究');
                for (let idx = 0; idx < 20; idx++) {
                    click(1386, 407)
                    sleep(500)
                }
            }
            if (addDefenseStudyTask) {
                console.log('加防御研究');
                for (let idx = 0; idx < 20; idx++) {
                    click(653, 411)
                    sleep(500)
                }
            }
            if (upgradeSkillsTask) {
                console.log('升级技能任务');
                click(872, 785)
                sleep(1000)
                click(1184, 734)
                sleep(1000)
            }
            if (petEvolutionTask) {
                console.log('宠物进化');
                res = el.petUpgradation()

                if (res.first()) {
                    p = res.first().point
                    click(p.x - 20, p.y + 10)
                    sleep(1000)

                    click(1182, 731)
                    sleep(1000)
                }
            }

            if (danTask) {
                modules.close()
                sleep(1000)
                modules.upDan()
            }

            if (sendAwayPetTask) {
                console.log('送走宠物任务');
                modules.petSort('down')
                p = _findImage(captureScreen(), images.read(files.path('./images/6.png')))

                if (p) {
                    click(p.x, p.y)
                    sleep(1000)

                    // 点击 选择
                    click(824, 773)
                    sleep(1000)

                    // 点击送走
                    click(888, 792)
                    sleep(1000)

                    // 确定送走
                    click(927, 595)
                    sleep(1000)

                    modules.ok()
                    modules.close()
                }
            }
            if (isObtainFirewallTask) {
                console.log('获得火墙术技能任务');
                click(1386, 441)
                sleep(1000)

                // 点击获得
                click(806, 788)
                sleep(1000)
                click(1168, 730)
                sleep(1000)
            }
            if (isObtainAdvancedTrainingTask) {
                console.log('获得被动技能高级训练3');
                click(1383, 176)
                sleep(1000)
                click(1142, 590)
                sleep(1000)

                // 点击获得
                click(806, 788)
                sleep(1000)
                click(1168, 730)
                sleep(1000)

                modules.ok()
            }
            if (addSkillTask) {
                console.log('获得火焰球技能任务');
                click(1138, 298)
                sleep(1000)

                click(806, 788)
                sleep(1000)
                click(1168, 730)
                sleep(1000)

                modules.ok()
            }
            if (isObtainLightningTask) {
                console.log('获得闪电技能任务');
                click(1146, 576)
                sleep(1000)

                click(806, 788)
                sleep(1000)
                click(1168, 730)
                sleep(1000)

                modules.ok()
            }
            if (assembleSkillTask) {
                console.log('装配技能任务');
                click(734, 788)
                sleep(1000)

                modules.ok()
            }
            if (elementCopyTask) {
                console.log('元素副本任务');
                click(507, 503)
                sleep(1000)
                click(1234, 735)
                sleep(1000)
            }
            if (isCopyGoldCoinTask) {
                console.log('金币副本任务');
                click(246, 308)
                sleep(1000)
                click(1234, 735)
                sleep(1000)
            }
            if (isHerbMedicineTask) {
                console.log('经验草副本任务');
                click(529, 315)
                sleep(1000)
                click(1234, 735)
                sleep(1000)
            }
            if (isWeaponExchangePetsTask) {
                console.log('武器交换宠物');
                click(949, 774)
                sleep(1000)
                click(1177, 739)
                sleep(1000)
            }
            if (isMineTask) {
                console.log('进入矿山任务');
                click(218, 513)
                sleep(1000)
                click(1234, 735)
                sleep(1000)
            }

            // 有些任务是打开对话框，需要关闭对话框
            modules.close()
        }
    },
    /** 关闭按钮, type: inner, external  */
    close(type) {
        sleep(50)
        if (type === undefined || type == 'inner') {
            p = _findImage(captureScreen(), images.read(files.path('./images/30.png')), { region: [859, 107, 1513 - 859, 623 - 107], threshold: 0.7 });
            if (p) {
                click(p.x + 20, p.y + 20)
                sleep(1000)
            }
        }
        sleep(50)
        if (type === undefined || type == 'external') {
            p = _findImage(captureScreen(), images.read(files.path('./images/62.png')), { region: [1003, 1, 1599 - 1003, 488 - 1] });
            if (p) {
                click(p.x + 30, p.y + 30)
                sleep(1000)
            }
        }

        sleep(50)
        p = _findImage(captureScreen(), images.read(files.path('./images/关闭应用.png')));
        if (p) {
            click(p.x + 30, p.y + 30)
            sleep(1000)
        }
    },
    /** 打boss */
    strikeBoss() {
        time = storage.get("strikeBossTime");
        currentTime = new Date().valueOf()

        if (time) {
            isExec = currentTime > time + (60 * 1000 * 10)
        } else {
            isExec = true
        }

        if (isExec) {
            click(988, 179)
            sleep(1000)

            storage.put("strikeBossTime", new Date().valueOf());
        }
    },
    ok() {
        // 领取奖励卡住，异常处理
        p = el.ok()
        if (p) {
            click(p.x, p.y)
            sleep(1000)
            return true
        }

    },
    /** 切换账号 */
    switchNum() {
        let isWitchNum = false
        p = _findImage(captureScreen(), images.read(files.path('./images/48.png')), { region: [1463, 17, 1576 - 1463, 120 - 17] });

        isExec = false

        time = storage.get("switchNumTime");
        currentTime = new Date().valueOf()

        if (time) {
            isExec = currentTime > time + (60 * 1000 * 60 * 1)
        } else {
            isExec = true
        }

        if (p && isExec) {
            console.log('切换账号');
            storage.put("switchNumTime", new Date().valueOf());

            click(p.x, p.y)
            sleep(1000)
            p = _findImage(captureScreen(), images.read(files.path('./images/49.png')), { region: [1173, 177, 1555 - 1173, 561 - 177] });

            if (p) {
                click(p.x, p.y)
                sleep(1000)

                // 点击账号
                click(845, 179)
                sleep(1000)

                p = _findImage(captureScreen(), images.read(files.path('./images/50.png')), { region: [224, 544, 481 - 224, 769 - 544] });
                if (p) {
                    click(p.x, p.y)
                    sleep(1000)

                    p = _findImage(captureScreen(), images.read(files.path('./images/ok1.png')))

                    if (p) {
                        click(p.x, p.y)
                        sleep(2000)
                        click(820, 594)
                        sleep(10000)

                        do {
                            p = _findImage(captureScreen(), images.read(files.path('./images/47.png'))) || _findImage(captureScreen(), images.read(files.path('./images/51.png')));
                            sleep(1000)
                        } while (!p);

                        if (p) {
                            modules.login()
                        }
                    }
                }
            }
        }
    },
    login() {
        p = _findImage(captureScreen(), images.read(files.path('./images/47.png')));
        sleep(1000)

        if (p) {
            click(p.x, p.y)
            sleep(2000)
        }

        p = _findImage(captureScreen(), images.read(files.path('./images/51.png')));

        if (p) {
            click(p.x, p.y)
            sleep(1000)
            click(804, 404)
            sleep(1000)

            do {
                p = _findImage(captureScreen(), images.read(files.path('./images/52.png')));
                sleep(1000)
                console.log('等待账号选择界面出现');
                gameStuckDetection()
            } while (!p);

            if (p) {
                sleep(3000)

                let currentAccount = storage.get('currentAccount')
                let accs = id("com.google.android.gms:id/account_name").find()
                let idx = accs.findIndex(item => item.text() == currentAccount)

                if (accs.length) {
                    acc = accs[idx + 1] ? accs[idx + 1] : accs[0]

                    console.log(`登录 ${acc.text()}`);
                    storage.put('currentAccount', acc.text())

                    acc.parent().parent().click()
                } else {
                    console.log('当前没有登录谷歌账号');
                }

                while (!el.isMain()) {
                    sleep(1000)
                    if (this.ok()) {
                        break
                    }
                    this.close()
                    gameStuckDetection()
                    modules.setGameName()
                    modules.noviceGuidance()
                }

                start()
            }

        }
    },
    /** 设置游戏名称 */
    setGameName() {
        p = _findImage(captureScreen(), images.read(files.path('./images/请输入id.png')), { region: [440, 199, 1156 - 440, 679 - 199] });
        if (p) {
            click(805, 448)
            sleep(1000)
            let acc = storage.get('currentAccount') || ''
            accArr = acc.split('@')

            if (accArr.length) {
                input(accArr[0])
                modules.ok()
                sleep(100)
                modules.ok()
                sleep(1000)
                modules.ok()
            }
        }
    },
    /** 新手引导 */
    noviceGuidance() {
        p = _findImage(captureScreen(), images.read(files.path('./images/新手引导.png')), { region: [80, 43, 540 - 80, 860 - 43] });
        if (p) {
            console.log('游戏引导中...');
            while (!el.isMain() && !findImage(captureScreen(), images.read(files.path('./images/游戏加载界面.png')))) {
                click(1424, 778)
                sleep(100)
                click(110, 438)
                sleep(100)
                click(535, 800)
                sleep(100)
                click(809, 663)
                sleep(100)
                click(798, 793)
                sleep(100)
                click(108, 207)
                sleep(100)
                click(1307, 488)
                sleep(100)
                click(1179, 730)
                sleep(100)
                click(1375, 201)
                sleep(100)
                click(313, 778)
                sleep(100)
                click(1156, 409)
                sleep(100)
                click(821, 313)
                sleep(100)
                click(446, 745)
                sleep(100)
                click(986, 371)
                sleep(100)
                click(1516, 66)
                sleep(100)

                img = captureScreen()
                p = _findImage(img, images.read(files.path('./images/按钮.png')));
                if (p) {
                    click(p.x + 50, p.y + 20)
                    sleep(200)
                }

                p = _findImage(img, images.read(files.path('./images/新手引导_1.png')))

                if (p) {
                    click(p.x + 50, p.y + 20)
                    sleep(200)
                }
            }
        }
    },
    /** 宠物排序 */
    petSort(sort, type) {
        sort = sort == undefined ? 'down' : sort
        if (type === undefined) type = '稀有度'

        p = el.isPetList()

        if (p) {
            // 稀有度
            p = _findImage(captureScreen(), images.read(files.path('./images/55.png')), { region: [584, 644, 1571 - 584, 896 - 644] });

            if (type == '稀有度' && !p || type == '获得' && p) {
                p = _findImage(captureScreen(), images.read(files.path('./images/56.png')), { region: [584, 644, 1571 - 584, 896 - 644] });
                if (p) {
                    click(p.x + 100, p.y + 30)
                    sleep(1000)
                    // 点击稀有按钮
                    click(p.x + 100, p.y - 30)
                    sleep(1000)
                }
            }

            currentSort = ''

            // 降序
            p = _findImage(captureScreen(), images.read(files.path('./images/57.png')), { region: [584, 644, 1571 - 584, 896 - 644] });

            if (p) {
                currentSort = 'down'
            }

            // 升序
            p = _findImage(captureScreen(), images.read(files.path('./images/58.png')), { region: [584, 644, 1571 - 584, 896 - 644] });

            if (p) {
                currentSort = 'up'
            }

            if (sort != currentSort) {
                p = _findImage(captureScreen(), images.read(files.path('./images/56.png')), { region: [584, 644, 1571 - 584, 896 - 644] });
                if (p) {
                    click(p.x + 260, p.y + 30)
                    sleep(1000)
                }
            }
        }
    },
    /** 获取宠物属性 */
    getPetAttribute(region) {
        img = captureScreen()
        // 级别
        level = ''
        levelNo = ''
        // 属性
        type = ''
        // 稀有度
        rarity = ''
        rarityNo = ''
        // 等级
        grade = ''
        isEquipped = false
        maxGrade = ''

        if (_findImage(img, images.read(files.path('./images/up/风.png')), { region })) {
            type = '风'
        } else if (_findImage(img, images.read(files.path('./images/up/火.png')), { region })) {
            type = '火'
        } else if (_findImage(img, images.read(files.path('./images/up/水.png')), { region })) {
            type = '水'
        } else if (_findImage(img, images.read(files.path('./images/up/光明.png')), { region })) {
            type = '光明'
        }

        if (_findImage(img, images.read(files.path('./images/up/未知.png')), { region, threshold: 0.8 })) {
            level = '?'
            levelNo = 1
        } else if (_findImage(img, images.read(files.path('./images/up/S+.png')), { region })) {
            level = 'S+'
            levelNo = 10
        } else if (_findImage(img, images.read(files.path('./images/up/B+.png')), { region })) {
            level = 'B+'
            levelNo = 5
        } else if (_findImage(img, images.read(files.path('./images/up/A++.png')), { region })) {
            level = 'A++'
            levelNo = 8
        } else if (_findImage(img, images.read(files.path('./images/up/A+.png')), { region })) {
            level = 'A+'
            levelNo = 7
        } else if (_findImage(img, images.read(files.path('./images/up/A.png')), { region })) {
            level = 'A'
            levelNo = 6
        } else if (_findImage(img, images.read(files.path('./images/up/B.png')), { region })) {
            level = 'B'
            levelNo = 4
        }

        if (_findImage(img, images.read(files.path('./images/up/传说.png')), { region })) {
            rarity = '传说'
            rarityNo = 5
            maxGrade = 999
        } else if (_findImage(img, images.read(files.path('./images/up/英雄.png')), { region })) {
            rarity = '英雄'
            rarityNo = 4
            maxGrade = 400
        } else if (_findImage(img, images.read(files.path('./images/up/唯一.png')), { region })) {
            rarity = '唯一'
            rarityNo = 3
            maxGrade = 300
        } else if (_findImage(img, images.read(files.path('./images/up/稀有.png')), { region })) {
            rarity = '稀有'
            rarityNo = 2
            maxGrade = 200
        } else if (_findImage(img, images.read(files.path('./images/up/普通.png')), { region })) {
            rarity = '普通'
            rarityNo = 1
            maxGrade = 100
        }

        if (_findImage(img, images.read(files.path('./images/up/宠物已装备标识.png')), { region })) {
            isEquipped = true
        }

        res = _ocr(images.clip(img, region[0], region[1] + 106, region[2], 40), "zh")
        if (res) {
            str = res.text.replace('l', '1')
            grade = parseInt(str)
        }

        return {
            region,
            type,
            level,
            rarity,
            levelNo,
            rarityNo,
            grade,
            isEquipped,
            maxGrade
        }
    },
    /** 获取宠物列表 */
    getPetList() {
        res = _matchTemplate(captureScreen(), images.read(files.path('./images/6.png')), { max: 35, region: [715, 206, 1567 - 715, 805 - 206] })

        petList = res.sortBy('top-left').points.map(p => {
            x = p.x - 88
            y = p.y - 112
            width = 110
            height = 140
            region = [x, y, width, height]

            return modules.getPetAttribute(region)
        })

        return petList
    },
    /** 升阶 */
    upDan() {
        if (el.isMain()) {
            console.log('开始升阶');
            p = _findImage(captureScreen(), images.read(files.path('./images/召唤师入口.png')), { region: [148, 714, 286 - 148, 847 - 714] })
            if (!p) return
            click(p.x, p.y)
            sleep(1000)

            p = _findImage(captureScreen(), images.read(files.path('./images/召唤师信息-升阶.png')))
            if (!p) return
            click(p.x, p.y)
            sleep(1000)

            res = _matchTemplate(captureScreen(), images.read(files.path('./images/6.png')), { max: 6, region: [732, 324, 1429 - 732, 518 - 324] })

            let demandList = res.sortBy('top-left').points.map(p => {
                x = p.x - 88
                y = p.y - 112
                width = 110
                height = 140
                region = [x, y, width, height]

                return modules.getPetAttribute(region)
            })

            modules.close()
            modules.close()

            p = el.mainPet()

            if (p) {
                click(p.x, p.y)
                sleep(2000)

                let rarity = []
                let type = []

                demandList.forEach(item => {
                    rarity.push(item.rarity)
                    type.push(item.type)
                })

                if (demandList.length) {
                    // 孵化对应属性的宠物
                    console.log('点击宠物信息');
                    click(110, 209)
                    sleep(3000)

                    // 获取过滤选项
                    rarity = removeDuplicates(rarity)
                    type = removeDuplicates(type)

                    // 设置宠物过滤
                    modules.filterPetList({ type })

                    // 排序
                    modules.petSort('down', '获得')

                    sleep(2000)

                    console.log('获取宠物列表');
                    petList = modules.getPetList()
                    petList = petList.filter(item => !item.isEquipped && (!type[0] || item.type == type[0]))


                    for (let idx = 0; idx < petList.length; idx++) {
                        let pet = petList[idx];
                        let upPet = demandList[0]

                        click(pet.region[0] + 50, pet.region[1] + 50)
                        sleep(1000)

                        if (pet.rarityNo > upPet.rarityNo) {
                            continue
                        }

                        console.log(`当前操作卡片为${JSON.stringify(pet)}`);
                        console.log(`需要升级为${JSON.stringify(upPet)}`);

                        // 进化宠物
                        if (pet.rarityNo < upPet.rarityNo) {
                            sleep(1000)

                            console.log(`需要卡片进化为[${upPet.rarity}], 当前为[${pet.rarity}]`);
                            modules.evolutionPet(upPet.rarityNo)

                            sleep(1000)
                            pet = modules.getPetAttribute(pet.region)
                            if (pet.rarityNo > upPet.rarityNo) {
                                console.log(`需要进化为[${upPet.rarity}], 当前为[${pet.rarity}], 不符合需求跳过当前卡片`);
                                continue
                            }
                        }

                        // 升级级别(重生)
                        if (pet.levelNo < upPet.levelNo) {
                            console.log(`需要升级为${upPet.level}, 当前为${pet.level}`);
                            sleep(1000)
                            modules.reborn(upPet.levelNo)
                        }

                        // 升级宠物
                        if ((pet.grade || 0) < pet.maxGrade) {
                            console.log(`需要提升等级为${upPet.grade}, 当前为${pet.grade}`);
                            sleep(1000)
                            modules.upgradationPet(true)
                        }

                        console.log(`升级后的卡片属性:`);
                        console.log(modules.getPetAttribute(pet.region))

                        demandList.splice(0, 1)

                        // 全部处理完，退出循环
                        if(!demandList.length) {
                            break
                        }
                    }

                    if (demandList.length) {
                        modules.close()
                        console.log(`缺少宠物, 需要孵化${demandList.length}个宠物`);
                        modules.incubate({ type: demandList[0].type, num: demandList.length })
                    } else {
                        modules.close()

                        p = _findImage(captureScreen(), images.read(files.path('./images/召唤师入口.png')), { region: [148, 714, 286 - 148, 847 - 714] })
                        if (!p) return
                        click(p.x, p.y)
                        sleep(1000)

                        p = _findImage(captureScreen(), images.read(files.path('./images/召唤师信息-升阶.png')))
                        if (!p) return
                        click(p.x, p.y)
                        sleep(1000)

                        res = _matchTemplate(captureScreen(), images.read(files.path('./images/39.png')), { region: [822, 310, 1359 - 822, 525 - 310] });
                        arr = res.sortBy('left').points

                        mResult = []

                        arr.forEach(p => {
                            click(p.x + 4, p.y + 4)
                            sleep(1000)

                            mResult = _matchTemplate(captureScreen(), images.read(files.path('./images/40.png')), { region: [749, 232, 1362 - 749, 679 - 232], max: 20 })
                            arr1 = mResult.sortBy("bottom-right").points

                            arr1 = arr1.filter(p => {
                                let x = p.x - 88
                                let y = p.y - 120
                                let width = 110
                                let height = 140

                                p = _findImage(captureScreen(), images.read(files.path('./images/up/正在选择.png')), { region: [x, y, width, height] })

                                if (!p) {
                                    return true
                                }
                            })

                            if (arr1.length) {
                                p = arr1[0]
                                click(p.x - 30, p.y - 40)
                                sleep(1000)

                                // 点击选择
                                p = _findImage(captureScreen(), images.read(files.path('./images/42.png')))
                                if (p) {
                                    click(p.x, p.y)
                                    sleep(1000)
                                }
                            } else {
                                click(1418, 188)
                                sleep(1000)
                            }
                        })

                        // 点击升阶
                        p = _findImage(captureScreen(), images.read(files.path('./images/41.png')))
                        if (p) {
                            click(p.x, p.y)
                            sleep(1000)

                            // 确认升阶
                            p = _findImage(captureScreen(), images.read(files.path('./images/41.png')))
                            if (p) {
                                click(p.x, p.y)
                                sleep(1000)

                                // 确定
                                p = _findImage(captureScreen(), images.read(files.path('./images/ok.png')))
                                if (p) {
                                    click(p.x, p.y)
                                    sleep(1000)
                                }
                            }
                        }
                    }
                }

                this.close()
            }
        }

    },
    /**  */
    // modules.filterPetList({ rarity: ['普通', '稀有'], type: ['风'] })
    /** 过滤宠物列表 */
    filterPetList(option) {
        if (!option) option = {}
        console.log('点击过滤按钮')
        click(1484, 808)
        sleep(1000)

        // option.level
        // option.rarity
        console.log('初始化');
        click(684, 734)
        sleep(1000)

        console.log('设置属性');
        click(478, 300)
        sleep(1000)

        option.type && option.type.forEach(type => {
            if (type == '火') {
                click(476, 362)
                sleep(500)
            } else if (type == '水') {
                click(474, 421)
                sleep(500)
            } else if (type == '风') {
                click(477, 479)
                sleep(500)
            } else if (type == '光明') {
                click(467, 543)
                sleep(500)
            } else if (type == '黑暗') {
                click(480, 603)
                sleep(500)
            }
        })

        // console.log('设置类型');
        // click(478,300)
        // sleep(500)

        console.log('设置稀有度');
        click(853, 296)
        sleep(1000)
        option.rarity && option.rarity.forEach(rarity => {
            if (rarity == '普通') {
                click(803, 358)
                sleep(500)
            } else if (rarity == '稀有') {
                click(894, 358)
                sleep(500)
            } else if (rarity == '唯一') {
                click(805, 424)
                sleep(500)
            } else if (rarity == '英雄') {
                click(914, 418)
                sleep(500)
            } else if (rarity == '传说') {
                click(807, 480)
                sleep(500)
            }
        })

        // console.log('设置剩余重生');
        // click(1060,300)
        // sleep(500)

        console.log('设置完成')
        click(915, 735)
        sleep(1000)
    },
    /** 购买元素石 */
    purchaseStone(type, num) {
        let buySuccess = false

        p = _findImage(captureScreen(), images.read(files.path('./images/主界面商店入口.png')));
        console.log(p);
        if (p) {
            click(p.x, p.y)
            sleep(3000)

            if (findImage(captureScreen(), images.read(files.path('./images/商店界面.png')))) {
                click(121, 537)
                sleep(2000)
                p = null

                if (type == '火') {
                    p = _findImage(captureScreen(), images.read(files.path('./images/up/火元素.png')));
                } else if (type == '风') {
                    p = _findImage(captureScreen(), images.read(files.path('./images/up/风元素.png')));
                } else if (type == '水') {
                    p = _findImage(captureScreen(), images.read(files.path('./images/up/水元素.png')));
                } else if (type == '光明') {
                    p = _findImage(captureScreen(), images.read(files.path('./images/up/光明元素.png')));
                } else if (type == '进化石') {
                    p = _findImage(captureScreen(), images.read(files.path('./images/up/进化石.png')))
                }

                if (p) {
                    click(p.x, p.y)
                    sleep(2000)

                    console.log('购买元素石');
                    p = _findImage(captureScreen(), images.read(files.path('./images/up/购买.png')));
                    if (p) {
                        let setNum = ''
                        do {
                            console.log('选择数量')
                            click(1311, 544)
                            sleep(500)
                            let res = _ocr(images.clip(captureScreen(), 985, 516, 1126 - 985, 589 - 516), "zh")

                            if (res) {
                                res.text = res.text.replace('I', 1)

                                // 钱不够，每次设置数量都相同
                                if (setNum == res.text) {
                                    console.log('购买进化石失败, 钱不够');
                                    buySuccess = false
                                    break
                                }
                                if (res) {
                                    setNum = res.text
                                }
                            } else {
                                console.log('没有读取到选择的数量');
                                buySuccess = false
                                break
                            }
                        } while (Number(setNum) <= Number(num));

                        console.log(`设置数量${setNum}, 需要购买数量${num}`);


                        if (Number(setNum) >= Number(num)) {
                            console.log('点击购买')
                            click(p.x, p.y)
                            sleep(1000)
                            console.log('确定购买')
                            click(924, 601)
                            sleep(3000)
                            modules.ok()
                            buySuccess = true
                        }
                    }
                }
                modules.close()
            }
        }

        return buySuccess
    },
    /** 卡loading重启 */
    stuckLoading() {
        let p = el._findMultiColors("#ea731b", [[0, 6, "#ea731b"], [2, 16, "#ea731b"]], { region: [719, 376, 155, 144], threshold: [0] })

        if (p) {
            loadingCount += 1
            console.log('卡loading' + loadingCount);
            if (loadingCount >= 40) {
                console.log('重启游戏');
                loadingCount = 0
                events.broadcast.emit("detection");
            }
        } else {
            loadingCount = 0
            console.log('卡loading， 游戏恢复正常');
        }
    },
    /** 自动加属性 */
    autoAddAttribute() {
        time = storage.get("autoAddAttributeTime");
        currentTime = new Date().valueOf()
        isExec = time ? currentTime > time + (60 * 1000 * 20) : true

        if (el.isMain() && isExec) {
            console.log('自动加属性');
            p = _findImage(captureScreen(), images.read(files.path('./images/召唤师入口.png')), { region: [148, 714, 286 - 148, 847 - 714] })
            if (p) {
                click(p.x, p.y)
                sleep(2000)

                if (el.isUserInfo()) {
                    // 点击成长
                    click(108, 320)
                    sleep(1000)

                    p = _findImage(captureScreen(), images.read(files.path('./images/加点.png')), { region: [277, 526, 1515 - 277, 667 - 526] })
                    if (p) {
                        do {
                            num = _ocr(images.clip(captureScreen(), 1194, 172, 1332 - 1194, 230 - 172), "zh").text;

                            if (parseInt(num) >= 20) {
                                click(413, 590)
                                sleep(1000)
                            } else {
                                break
                            }
                            modules.ok()
                        } while (num);
                    }
                }
            }

            storage.put("autoAddAttributeTime", new Date().valueOf());
            this.close()
        }
    },
    /** 自动研究 */
    autoResearch() {
        time = storage.get("autoResearchTime");
        currentTime = new Date().valueOf()
        isExec = time ? currentTime > time + (60 * 1000 * 20) : true

        if (el.isMain() && isExec) {
            console.log('自动研究');
            p = _findImage(captureScreen(), images.read(files.path('./images/召唤师入口.png')), { region: [148, 714, 286 - 148, 847 - 714] })

            if (p) {
                click(p.x, p.y)
                sleep(2000)

                // 点击研究
                click(110, 428)
                sleep(1000)

                let newVal = ''
                let result = ''

                do {
                    if (result && result.text) {
                        newVal = result.text
                    }
                    click(380, 406)
                    click(1000)
                    result = _ocr(images.clip(captureScreen(), 579, 42, 670 - 579, 83 - 42), "zh");
                    modules.ok()
                } while (newVal != result.text);
            }

            storage.put("autoResearchTime", new Date().valueOf());
            this.close()
        }
    },
    /** 自动挖矿 */
    autoMining() {

    },
    /** 自动装最好装备 */
    autoMining() {

    },
    /** 领取新手奖励 */
    getNoviceRewards() {

    },
    /** 自动装备最新技能 */
    autoEquipSkill() {

    },
    /** 获取用户信息 */
    getUserInfo() {
        if (el.isMain()) {
            let img = captureScreen()
            let res = _ocr(images.clip(img, 139, 53, 360 - 139, 88 - 53), "zh")
            let name = ''

            if (res && res.text) {
                name = res.text
            }

            return { name }
        }

        return {}
    },
    /** 设置游戏环境 */
    setGame() {
        let currentAccount = storage.get('currentAccount')

        if (currentAccount) {
            let isSet = storage.get(`set_${currentAccount}`)

            if (!isSet) {
                console.log('设置游戏环境');
                let p = _findImage(captureScreen(), images.read(files.path('./images/48.png')), { region: [1463, 17, 1576 - 1463, 120 - 17] });
                if (p) {
                    click(p.x, p.y)
                    sleep(1000)

                    p = _findImage(captureScreen(), images.read(files.path('./images/49.png')), { region: [1173, 177, 1555 - 1173, 561 - 177] });

                    if (p) {
                        click(p.x, p.y)
                        sleep(1000)

                        // 设置界面
                        p = _findImage(captureScreen(), images.read(files.path('./images/设定.png')), { region: [224, 159, 346 - 224, 228 - 159] });
                        if (p) {
                            click(441, 175)
                            sleep(1000)

                            click(573, 267)
                            sleep(1000)
                            click(573, 267)
                            sleep(1000)

                            res = _matchTemplate(captureScreen(), images.read(files.path('./images/关闭.png')), { region: [527, 334, 638 - 527, 581 - 334] });
                            arr = res.sortBy('top').points

                            if (arr.length) {
                                arr.forEach(p => {
                                    click(p.x + 20, p.y - 13)
                                    sleep(1000)
                                })

                                storage.put(`set_${currentAccount}`, true)
                            }

                            this.close()
                        }
                    }
                }
            }
        }
    }
}

const pages = {
    mainDo() {
        if (el.isMain()) {
            modules.doTasks()
            modules.receiveReward()
            modules.strikeBoss()
            modules.switchNum()
            modules.autoAddAttribute()
            modules.autoResearch()
            modules.setGame()
        }
    }
}

function random(min, max) {
    return Math.round(Math.random() * (max - min)) + min;
}

function start() {
    endWhile = false

    do {
        gameStuckDetection()
        modules.stuckLoading()
        sleep(1000)
        if (el.isMain()) {
            endWhile = true
            while (true) {
                gameStuckDetection()
                modules.stuckLoading()
                sleep(100)
                pages.mainDo()

                modules.ok()
                modules.close()
            }
        } else {
            if (currentPackage() == 'com.studiolb.tamingmaster.global') {
                p = _findImage(captureScreen(), images.read(files.path('./images/47.png')));

                if (p) {
                    click(p.x, p.y)
                    sleep(1000)
                }

                // 卡住，异常处理
                modules.ok()
                modules.close()
                modules.login()
                modules.noviceGuidance()
            } else {
                app.launchPackage('com.studiolb.tamingmaster.global')
                sleep(5000)
            }
        }
    } while (!endWhile);
}

sleep(3000)

start()

